package cn.qianxun.meta.word.replace;

import cn.qianxun.meta.word.util.AsposeUtil;
import cn.qianxun.meta.word.vo.GenerateTableVO;
import cn.qianxun.meta.word.vo.MergeTableParamVO;
import com.aspose.words.*;
import org.springframework.util.CollectionUtils;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author fuzhilin
 * @Date 2021/12/2 0002 9:41
 * @Description
 */
public class ReplaceAndInsertTable implements IReplacingCallback {
    private String key;
    private GenerateTableVO tableVO;

    public ReplaceAndInsertTable(String key, GenerateTableVO tableVO) {
        this.key = key;
        this.tableVO = tableVO;
    }

    @Override
    public int replacing(ReplacingArgs e) throws Exception {
        //获取当前节点
        Node currentNode = e.getMatchNode();
        //节点拆分处理当前匹配字段
        splitRun(currentNode, e.getMatchOffset());
        //获取当前文档
        Document document = (Document) currentNode.getDocument();
        DocumentBuilder builder = new DocumentBuilder(document);
        //将光标移动到指定节点
        builder.moveTo(currentNode);
        Table table = builder.startTable();

        // 表头
        List<String> title = tableVO.getTitle();
        List<List<String>> values = tableVO.getValues();

        double width = tableVO.getWidth();

        // 添加表头
        table.getRows().add(createRow(title.size(), title.toArray(new String[title.size()]), document, true));
        // 添加参数值
        for (int i = 0; i < values.size(); i++) {
            List<String> value = values.get(i);
            if (value != null && !value.isEmpty()) {
                table.getRows().add(createRow(value.size(), value.toArray(new String[value.size()]), document, false));
            }
        }
        //如果不为空 说明需要合并
        if (!CollectionUtils.isEmpty(tableVO.getMergeTableParamList())) {
            AsposeUtil.MergeSpecifiedCells(document, tableVO.getMergeTableParamList());
        }
        if (0 != width) {
            table.setPreferredWidth(PreferredWidth.fromPoints(width));
        }
        return ReplaceAction.SKIP;
    }

    /**
     * 创建列
     *
     * @param value
     * @param doc
     * @return
     */
    static Cell createCell(String value, Document doc, boolean isHeader) {
        Cell c1 = new Cell(doc);
        Paragraph p = new Paragraph(doc);
        Run r = new Run(doc, value);
        r.getFont().setName("仿宋GB2312");
        r.getFont().setSize(14);
        if (isHeader || "筛查内容".equals(value)) {
            if ("学生姓名".equals(value)) {
                r.getFont().setBold(false);
            } else {
                r.getFont().setBold(true);
            }
        } else {
            r.getFont().setBold(false);
        }
        p.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        p.appendChild(r);
        c1.appendChild(p);
        return c1;
    }

    /**
     * 创建行
     *
     * @param columnCount
     * @param columnValues
     * @param doc
     * @return
     */
    static Row createRow(int columnCount, String[] columnValues, Document doc, boolean isHeader) {
        Row r2 = new Row(doc);
        /*r2.getRowFormat().setTopPadding(5d);
        r2.getRowFormat().setBottomPadding(5d);*/
        for (int i = 0; i < columnCount; i++) {
            if (columnValues.length > i) {
                Cell cell = createCell(columnValues[i], doc, isHeader);
                r2.getCells().add(cell);
                cell.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            } else {
                Cell cell = createCell("", doc, isHeader);
                r2.getCells().add(cell);
                cell.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            }

        }
        return r2;
    }

    /**
     * 替换参数位置
     *
     * @param currentNode
     * @param position
     */
    private void splitRun(Node currentNode, int position) {
        String text = currentNode.getText();
        Node newNode = currentNode.deepClone(true);
        if (text.length() >= position + this.key.length()) {
            ((Run) currentNode).setText(text.substring(position + this.key.length()));
        } else {
            int morlength = position + this.key.length() - text.length();
            ((Run) currentNode).setText("");
            Node tmpnode = currentNode;
            for (int i = 0; i < this.key.length(); i++) {
                System.out.println(i);
                tmpnode = tmpnode.getNextSibling();
                String tmptext = tmpnode.getText();
                System.out.println(tmptext);
                System.out.println(morlength);
                System.out.println("--------" + (tmptext.length() >= morlength));

                if (tmptext.length() >= morlength) {
                    ((Run) tmpnode).setText(tmptext.substring(morlength));
                    break;
                } else {
                    morlength = morlength - tmptext.length();
                    ((Run) tmpnode).setText("");
                }
            }
        }
        if (position > 0) {
            ((Run) newNode).setText(text.substring(0, position));
            currentNode.getParentNode().insertBefore(newNode, currentNode);
        }
    }

    /**
     * 设置表体的格式
     */
    public static void setTableBodyFormat(DocumentBuilder builder) throws Exception {
        //清除格式
        builder.getCellFormat().clearFormatting();
        //设置单元格垂直
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        //单元格背景颜色设置
        builder.getCellFormat().getShading().setBackgroundPatternColor(new Color(253, 253, 253, 255));
        //单元格边框颜色设置
        builder.getRowFormat().getBorders().setColor(new Color(1, 1, 1));
        //设置字体颜色
        builder.getFont().setColor(new Color(1, 1, 1));
        //这行代码禁用单元格中的文本自动换行功能
        builder.getCellFormat().setWrapText(false);
    }

    public static void main(String[] args) throws Exception {
        GenerateTableVO generateTableVO = new GenerateTableVO();
        generateTableVO.setTitle(Arrays.asList("", "心理健康状况不佳", "心理健康状况不佳"));
        ArrayList<List<String>> lists = new ArrayList<>();
        lists.add(Arrays.asList("", "人数", "占比"));
        lists.add(Arrays.asList("小学", "75", "12%"));
        lists.add(Arrays.asList("初中", "65", "11%"));
        lists.add(Arrays.asList("大学", "122", "23%"));
        generateTableVO.setValues(lists);
        ArrayList<MergeTableParamVO> mergeTableParamVOS = new ArrayList<>();
        MergeTableParamVO paramVO = new MergeTableParamVO();
        paramVO.setBorderType(BorderType.DIAGONAL_DOWN);
        mergeTableParamVOS.add(new MergeTableParamVO().setStartLine(0).setStartColumn(0).setEndLine(1).setEndColumn(0));
        mergeTableParamVOS.add(new MergeTableParamVO().setStartLine(0).setStartColumn(1).setEndLine(0).setEndColumn(2));
        generateTableVO.setMergeTableParamList(mergeTableParamVOS);


        // 实例化一个document对象
        Document document = new Document();
        // 创建一个DocumentBuilder类的对象，并使用Document对象对其进行初始化
        DocumentBuilder builder = new DocumentBuilder(document);
        // 表头
        List<String> title = generateTableVO.getTitle();
        List<List<String>> values = generateTableVO.getValues();
        Table table = builder.startTable();
        // 添加表头
        table.getRows().add(createRow(title.size(), title.toArray(new String[title.size()]), document, true));
        // 添加参数值
        for (int i = 0; i < values.size(); i++) {
            List<String> value = values.get(i);
            if (value != null && !value.isEmpty()) {
                table.getRows().add(createRow(value.size(), value.toArray(new String[value.size()]), document, false));
            }
        }
        //如果不为空 说明需要合并
        if (!CollectionUtils.isEmpty(generateTableVO.getMergeTableParamList())) {
            AsposeUtil.MergeSpecifiedCells(document, generateTableVO.getMergeTableParamList());
        }
        document.save("D://saveFile//合并//hebing1.docx");
    }
}
